package edu.rutgers.moko;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;

import edu.rutgers.moko.data.FieldAccess;
import edu.rutgers.moko.data.ProtectedRule;
import edu.rutgers.moko.data.util.FieldAccessUtil;
import edu.rutgers.moko.data.util.Flag;
import edu.rutgers.moko.data.util.PrivacyMode;
import edu.rutgers.moko.data.util.ProtectedAccess;
import edu.rutgers.moko.data.util.SecurityUtil;

/**
 * 
 * @author Darja Krushevskaja
 * 
 */

public class MessageServlet extends HttpServlet {

	private static final long serialVersionUID = -7100991365098853668L;
	//private final File dir = new File("/home/dashali/Documents/school/projects/server");
	private final File dir = new File("/home/root/server");
	private final File msgs = new File(dir, "msgs.txt");
	//msg format: time \t sender \t message \t rule
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        PrintWriter pw = null;
        StringBuilder msg = new StringBuilder();
        
        //time
        DateFormat dateFormat = new SimpleDateFormat("MM/dd HH:mm");
        Date date = new Date();
        
        msg.append(dateFormat.format(date)).append("\t");
        
        //sender
        String sender = req.getParameter("sender").replace("\t", " ").trim();
        msg.append(sender).append("\t");
        
        //msg
        String txt = req.getParameter("msg").replace("\t", " ").trim();
        msg.append(txt).append("\t");
        
        //type
       
		FieldAccess fa = new FieldAccess();
		
		fa.setPrivacyMode(PrivacyMode.getByField(req.getParameter("pm")));
		if (fa.getPrivacyMode().equals(PrivacyMode.PROTECTED)) {
			ProtectedAccess pam = ProtectedAccess.getByField(req.getParameter("act"));
			if(pam!=null){
				ProtectedRule pr = new ProtectedRule(pam);
	
				pr.setFlag(Flag.getByTitle(req.getParameter("flag")));
				String loc = req.getParameter("loc");
				String ap = req.getParameter("ap");
				String cli = req.getParameter("cl");
				pr.validateAndSetControlValues(loc, ap, cli);
				fa.addProtectedRule(pr);
			}
			if (fa.getProtectedRules().size() == 0) {
				fa.setPrivacyMode(PrivacyMode.PRIVATE);
			}
		}
		msg.append(fa.getFieldAccessAsRule());
		try {
			if (sender.length()>0 || txt.length() > 0) {
				pw = new PrintWriter(new FileWriter(msgs.getCanonicalPath(), true), true);
				pw.println(msg.toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			
			pw.close();
		}
       
		
		res.sendRedirect("/msg");
	}



	@SuppressWarnings("unchecked")
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		res.setContentType("text/html; charset=ISO-8859-4");
		FieldAccessUtil faUtil = new FieldAccessUtil(new ArrayList<String>());

		PrintWriter out = res.getWriter();

		out.println("<html>");
		out.println("<head><title>OM >> Leave a message</title>");
		out.println(ServletUtil.showhideJs() + " " + ServletUtil.css());
		out.println("</head>");

		out.println("<body>");
		out.println("<h1>OM >> Leave a message</h1>");
		out.print("<a href=\"/state\">Home</a>");
		out.print(" | <a href=\"/rss\">RSS</a>");
		out.print(" | <a href=\"/msg\">Messages</a>");
		if(SecurityUtil.localAccess(req)){
			out.print(" | <a href=\"/scs\">Adjust sequrity controls</a>");
		}
		
	    out.println("<br><FORM ACTION=\"/msg\" METHOD=\"POST\">");
	    out.println("<table class=\"border\"><tr><th>From*:</th><td colspan=\"2\"> <input type=\"text\" name=\"sender\"></td></tr>");
	    out.println("<tr><th>Message type:</th><td colspan=\"2\"><select name=\"pm\" id=\"pm\" onChange=\"showhide('pm','prot')\">");
		for (PrivacyMode pm : PrivacyMode.valuesAsList()) {
			out.print("<option value=\""+pm.name()+"\">"+pm.modelName()+"</option>");
		}
		out.println("</select></td></tr>");
		out.println("<tbody id=\"prot\" style=\"display: none;\">");
		
		out.println("<tr ><td>&nbsp;</td><td colspan=\"2\">");
		for (Flag flag : Flag.valuesAsList()) {
			out.print("<input type=\"radio\" name=\"flag\" value=\"\""+faUtil.flagChecked(null, flag) +">"+flag.title());
		}
		out.print("</td></tr>");
		out.println("<tr><td>&nbsp;</td><td>");
		out.print("<input type=\"radio\" name=\"act\" value=\""+ProtectedAccess.LOCATION.field()+"\">"+ProtectedAccess.LOCATION.restriction());
		out.print(": (x1:x2:y1:y2)</td>");
		out.print("<td><input type=\"text\" name=\"loc\" value=\"\"><br>");
		out.print("</td></tr>");
		out.println("<tr><td>&nbsp;</td><td>");
		out.print("<input type=\"radio\" name=\"act\" value=\""+ProtectedAccess.AP.field()+"\">"+ProtectedAccess.AP.restriction());
		out.print(": (AP_MAC)</td>");
		out.print("<td><input type=\"text\" name=\"ap\" value=\"\"><br>");
		out.print("</td></tr>");
		out.println("<tr><td>&nbsp;</td><td>");
	    out.print("<input type=\"radio\" name=\"act\" value=\""+ProtectedAccess.CLIENT.field()+"\">"+ProtectedAccess.CLIENT.restriction());
		out.print(": (client_ip:subnet_mask)</td>");
		out.print("<td><input type=\"text\" name=\"cl\" value=\"\"><br>");
		out.print("</td></tr>");
		out.print("</tbody>");
        out.println("<tr><th>Message*:</th><td> <textarea rows=\"2\" cols=\"20\" name=\"msg\"></textarea></td></tr>");
        
        out.println("<tr><th colspan=\"2\"><INPUT TYPE=\"submit\" VALUE=\"Send the message\"></td></tr></td></tr></table>");
        out.println("</FORM>");
        
        out.println("<h1>History</h1>");
        out.println("<table class=\"border\"><thead><tr>");
        out.println("<tr><th>When</th><th>From</th><th>Message</th></tr></thead>");
        
        if(msgs.exists()){
        	List<String> lines = FileUtils.readLines(msgs);
			Collections.reverse(lines);
			for (String line : lines) {
				String[] props = line.split("\t");
				if(props.length>3){
					line = line.replace(props[0], "").trim();
					line = line.replace(props[1], "").trim();
					line = line.replace(props[2], "").trim();
					FieldAccess fa = new FieldAccess();
					fa.setValuesFromString(line);
					if(faUtil.showMessage(req.getRemoteAddr(), fa)){
						out.println("<tr><td>"+props[0]+"</td><td>"+props[1]+"</td><td>"+props[2]+"</td></tr>");
					}
				}
			}
        }
        out.println("</table>");
		out.print("<br/><br/><div id=\"footer\"><center><b>OM project for internet services</b> 2009<br>Darja Krushevskaja &amp;for more information: darja@cs</center></div>");
		out.println("</body>");
		out.println("</html>");

		out.close();
	}
}
